package com.zhxy.util.message;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;

public class JavaMessageCodec implements MessageCodec {

	@Override
	public ByteBuffer encode(Object message) {
		
		try {
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(output);
			out.writeObject(message);
			out.flush();
			byte[] b = output.toByteArray();
			ByteBuffer buf = ByteBuffer.allocate(b.length + 4);
			buf.putInt(b.length);
			buf.put(b);
			buf.flip();
			return buf;
			
		} catch (IOException e) {
			throw new MessageCodecException(e);
		}
	}

	@Override
	public Object decode(ByteBuffer buf) {
		try {
			if (buf.remaining() < 4)
				return null;
			int size = buf.getInt();
			if (buf.remaining() < size)
				return null;
			
			byte[] b = new byte[size];
			buf.get(b);
			return new ObjectInputStream(new ByteArrayInputStream(b)).readObject();
		} catch (Exception e) {
			throw new MessageCodecException(e);
		}
	}

}
